package main

import (
	"context"
	"time"

	"github.com/kataras/iris/v12"
	"github.com/kataras/iris/v12/middleware/recover"
	"github.com/kataras/iris/v12/middleware/requestid"
)

type HttpService struct {
	app         *iris.Application
	Addr        string
	LoggerLevel string
}

func newHttpService() *HttpService {
	return &HttpService{
		app:         iris.New(),
		Addr:        ":6800",
		LoggerLevel: "debug",
	}
}

func (serv *HttpService) Run() {
	// 设置日志
	setLogger(serv.app, serv.LoggerLevel)
	// 设置全局组件
	useGlobalMiddleware(serv.app)

	routeEcho(serv.app)
	shutdown(serv.app)

	// Run
	serv.app.Run(
		iris.Addr(serv.Addr),
		iris.WithoutInterruptHandler,
		iris.WithoutServerError(iris.ErrServerClosed),
	)
}

// 设置地址
func (serv *HttpService) SetAddr(addr string) *HttpService {
	serv.Addr = addr
	return serv
}

// 注册路由
func (serv *HttpService) AddRoute(routeFun func(app *iris.Application)) *HttpService {
	routeFun(serv.app)
	return serv
}

// 设置Logger
func setLogger(app *iris.Application, LoggerLevel string) {
	app.Logger().SetLevel(LoggerLevel)
	if LoggerLevel == "debug" {
		app.Logger().Debugf(`Log level set to "debug"`)
	}
}

// 全局中间件
func useGlobalMiddleware(app *iris.Application) {
	// Register the requestid middleware
	// before recover so current Context.GetID() contains the info on panic logs.
	app.UseRouter(requestid.New())

	// Register the recovery, after accesslog and recover,
	// before end-developer's middleware.
	app.UseRouter(recover.New())
}

// 关闭服务
func shutdown(app *iris.Application) {
	iris.RegisterOnInterrupt(func() {
		timeout := 2 * time.Second
		ctx, cancel := context.WithTimeout(context.Background(), timeout)
		defer cancel()

		// todo

		//关闭所有主机
		app.Shutdown(ctx)
	})
}

// 添加Echo路由
func routeEcho(app *iris.Application) {
	app.Get("/echo", func(ctx iris.Context) {
		ctx.StopWithJSON(200, iris.Map{
			"unix_time": time.Now().Format(time.RFC3339),
			"errno":     0,
			"message":   "ok",
		})
	})
}
